package cn.com.cc.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class DownLoadResponse {
	
	/** reponse设置头信息*/
	private String contentType;
	
	private HttpServletResponse response;
	
	/** 读取块大小*/
	private int size;
	
	private ServletContext context;
	
	private boolean autoCloseInputStream;
	
	public boolean isAutoCloseInputStream() {
		return autoCloseInputStream;
	}

	public void setAutoCloseInputStream(boolean autoCloseInputStream) {
		this.autoCloseInputStream = autoCloseInputStream;
	}

	public DownLoadResponse(ServletContext context, HttpServletResponse response){
		this.context = context;
		this.response = response;
		size = 65535;
		autoCloseInputStream = true;
		contentType = "application/x-msdownload";
	}
	
	public DownLoadResponse(HttpServletResponse response){
		this.context = null;
		this.response = response;
		size = 65535;
		autoCloseInputStream = true;
		contentType = "application/x-msdownload";
	}
	
	public DownLoadResponse(HttpServletResponse response, String contentType){
		this(response);
		this.contentType = contentType;
	}
	
	public DownLoadResponse(ServletContext context,HttpServletResponse response, String contentType){
		this(context, response);
		this.contentType = contentType;
	}
	/**
	 * 	
	 * @param path					下载文件路径
	 * @param fileName				下载后文件名
	 * @throws IOException
	 */
	public void downLoadFile(String path, String fileName) throws IOException{
		File file = new File(path);
		if(!file.exists()){
			if(context != null){
				file = new File(context.getRealPath(path));
			}
			if(!file.exists()){
				throw new IOException("file not found,file path =" + path);
			}
		}
		if(!file.canRead()){
			throw new IOException("don't have permission to read file,file path=" + path);
		}
		if(fileName == null || "".equals(fileName)){
			fileName = file.getName();
		}
		response.setContentType(contentType);
		response.setHeader("Content-Disposition", String.valueOf((new StringBuffer("attachment; filename=")).append(new String(fileName.getBytes(), "iso-8859-1"))));
		ServletOutputStream out = response.getOutputStream();
		FileInputStream in = new FileInputStream(file);
		int len = 0;
		byte[] buf = new byte[size];
		while((len = in.read(buf)) != -1){
			out.write(buf, 0, len);
		}
		in.close();
	}
	
	/**
	 * 
	 * @param input					下载文件流
	 * @param fileName				下载后文件名
	 * @throws ServletException
	 * @throws IOException
	 */
	public void downLoadInputStream(InputStream input, String fileName) throws ServletException, IOException{
		if(fileName == null || "".equals(fileName.trim())){
			throw new ServletException("filename must not be null");
		}
		if(input == null){
			throw new ServletException("file inputstream must not be null");
		}
		if(FileInputStream.class.isInstance(input)){
			downLoadFileInputStream(input, fileName);
		}else{
			downloadInputStreamByBytesArray(input, fileName);
		}
	}
	
	public void downLoadFileInputStream(InputStream input, String fileName) throws IOException, ServletException{
		if(response == null){
			throw new ServletException("reponse must not be null");
		}
		response.setContentType(contentType);
		response.setHeader("Content-Disposition", String.valueOf((new StringBuffer("attachment; filename=")).append(new String(fileName.getBytes(), "iso-8859-1"))));
		ServletOutputStream out = response.getOutputStream();
		byte[] buf = new byte[size];
		int len = 0;
		while((len = input.read(buf)) != -1){
			out.write(buf, 0, len);
		}
		if(isAutoCloseInputStream()){
			input.close();
		}
	}
	
	public void downloadInputStreamByBytesArray(InputStream input, String fileName) throws IOException, ServletException{
		BufferedInputStream bufferedinputstream = new BufferedInputStream(input);
        ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
        BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(bytearrayoutputstream);
        for(int i = -1; (i = bufferedinputstream.read()) != -1;){
            bufferedoutputstream.write(i);
        }
        bufferedoutputstream.flush();
        bytearrayoutputstream.flush();
        downLoadBytes(bytearrayoutputstream.toByteArray(), fileName);
        bufferedinputstream.close();
        bytearrayoutputstream.close();
        bufferedoutputstream.close();
        if(isAutoCloseInputStream()){
            input.close();
        }
	}
	
	public void downLoadBytes(byte[] bytes, String fileName) throws ServletException, IOException{
		if(response == null){
			throw new ServletException("reponse must not be null");
		}
		if(bytes == null){
			throw new ServletException("byte array must not be null");
		}
		response.setContentType(contentType);
		response.setContentLength(bytes.length);
		response.setHeader("Content-Disposition", String.valueOf((new StringBuffer("attachment; filename=")).append(new String(fileName.getBytes(), "iso-8859-1"))));
		ServletOutputStream out = response.getOutputStream();
		out.write(bytes);
		bytes = null;
	}
	

}
